package de.nak.fireDepartment.visitorAction;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.web.struts.LookupDispatchActionSupport;

import de.nak.fireDepartment.actionForms.DepartmentForm;
import de.nak.fireDepartment.model.Department;
import de.nak.fireDepartment.service.DepartmentService;

/**
 * Action that shows a department
 * 
 * @author Sven Redelin
 */
public class DepartmentAction extends LookupDispatchActionSupport {

	/**
	 * This method shows the selected departdment into the departmentForm
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return actionforward
	 * @throws Exception
	 */
	public ActionForward showDepartment(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		// ActionForm => DepartmentForm
		DepartmentForm departmentForm = (DepartmentForm) form;
		DepartmentService departmentService = (DepartmentService) getWebApplicationContext().getBean("departmentService");
		
		// if no line selected display error
		if(departmentForm.getSelectedKey()==null){
			departmentForm.setErrorCode("text.error.selectedKey");
			return mapping.findForward("cancel");
		}
		
		// get department
		Department department = departmentService.showDepartment(departmentForm.getSelectedKey());
		
		// if department has no image set default image
		if (department.getImageURL() == null || department.getImageURL().equals("")){
			department.setImageURL("/FireDepartmentManagement/images/layout/noImage.jpg");
		}
		
		// store department and data in Form
		departmentForm.setDepartment(department);
		departmentForm.setErrorCode("");
		// Return result
		return mapping.findForward("show");
	}

	/** {@inheritDoc} */
	@Override
	protected Map<String, String> getKeyMethodMap() {
		Map<String, String> map = new HashMap<String, String>();
		map.put("button.show", "showDepartment");
		return map;
	}
}
